/*
	The Raja Toolkit.
	Copyright (C) 2011 Raja-Toolkit Foundation

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 3.0 of the License, or (at your option) any later version.

	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "../framebuffer.hpp"

#include "gles2_internal.hpp"

#include <FreeImage.h>

using namespace std;

namespace raja
{
namespace render
{


framebuffer* framebuffer::create(sampler2 *color, sampler2 *depth)
{
	GLuint	fbo, old_fbo;

	GL_CHECK( glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&old_fbo)) );

	GL_CHECK( glGenFramebuffers(1, &fbo) );
	GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, fbo) );
	if( color )
		GL_CHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color->get_tex_id(), 0) );
	if( depth )
		GL_CHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth->get_tex_id(), 0) );

	framebuffer*	fb	= new framebuffer();
	fb->__fbo		= fbo;
	fb->__old_fbo	= old_fbo;
	fb->__color		= color;
	fb->__depth		= depth;

	GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, old_fbo) );

	return fb;
}

void framebuffer::attach_color(sampler2 *color)
{
	push();

	if( color )
		GL_CHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color->get_tex_id(), 0) );
	__color	= color;

	pop();
}

void framebuffer::attach_depth(sampler2 *depth)
{
	push();

	if( depth )
		GL_CHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth->get_tex_id(), 0) );
	__depth	= depth;

	pop();
}

void framebuffer::push()
{
	GL_CHECK( glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&__old_fbo)) );

	GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, __fbo) );
}

void framebuffer::pop()
{
	GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, __old_fbo) );
}

} // namespace render
} // namespace raja


